<?php
// +----------------------------------------------------------------------
// | Author: 黄泽宏 <2623213969@qq.com>
// +----------------------------------------------------------------------

namespace app\home\controller;
use think\Controller;
/**
 * 前台首页控制器
 * 主要获取首页聚合数据
 */
class ActivityController extends Controller {
       private $wx_config = array();
       public function _initialize()
       {
           $this->wx_config = config('WX_CONFIG');
       }

    /**
        * 卡片扫描
        * @author HZH
        * **/
       public function card(){
               $only = input('param.only');
               $qrcode = db("prize_qrcode")->where(array("only"=>$only))->find();
               if($qrcode['status']==0){
                   $title = "红包未开启！";
                   $this->assign("qrcode_title",$title);
                   return $this->fetch('noredenvelope');
                   exit;
               }else if($qrcode['status']==1){
                   session('qrcode_id',$qrcode['id']);
                   header("Location:".U('index'));
                   exit;
               }else{
                   $title = "红包已使用过！";
                   $this->assign("qrcode_title",$title);
                   return $this->fetch('noredenvelope');
                   exit; 
               }
       }
       /**
        * 扫描是否关注
        * @author HZH
        * **/
       public function smsfgz(){
            define("TOKEN", "huangmai");//定义识别码 
            $echostr_data = file_get_contents('php://input');
            $echostr_arr = (array)simplexml_load_string($echostr_data, 'SimpleXMLElement', LIBXML_NOCDATA);
            $this->menu();
            $this->responseMsg(); 
       }
       /**
        * 微信关注页面
        * @author HZH
        */
       public function follow_wx(){
            return $this->fetch('follow_wx');
       }
       
       /**
        * 动态检测客户是否关注公众号
        * @author HZH
        */
       
       public function check_follow(){
           $openid = session('openid');
           $access_token = session('token');
           if(empty($openid)||empty($access_token)){
               $this->ajaxReturn(array('code'=>-1,'result'=>Url('index')));
           }else{
               $wx_union_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$openid}&lang=zh_CN";
               $wx_union = curl_request($wx_union_url);
               $wx_union_array = json_decode($wx_union,true);
               if(empty($wx_union_array['subscribe'])||$wx_union_array['subscribe']==0){
                   $this->ajaxReturn(array('code'=>0,'result'=>'Unfollow'));
               }else{
                   $this->ajaxReturn(array('code'=>1,'result'=>Url('User/filling')));
               }
           }
       }

       
/*********************************************************/
/*****************红包页面逻辑*****************/
/*********************************************************/       
    /**
    * 红包
    * @author HZH
    */
   public function redenvelope(){
        return $this->fetch('redenvelope');
   }
    /**
     * 中奖概率
     */
    public function ajax_probability(){
        $data = input('param.');
        $qrcode = db("prize_qrcode")->where(array("id"=>session('qrcode_id')))->find();
        if($qrcode['status']==2){
            $this->error("红包已经领取过！");
        }
        $activity = db('prize_config')->select();
        foreach ($activity as $key => $val) {   
            $arr[$val['id']] = $val['chance'];   
            $varr[$val['id']] = $val['prize'];   
        }   
        $rid = $this->get_rand($arr); //根据概率获取奖项id   
        $res = $varr[$rid]; //中奖项   
        $qrcode = db("prize_qrcode")->where(array("id"=>session('qrcode_id')))->update(['status'=>2]);
        $rel['user_id'] = session('user_id');
        $rel['openid'] = session('openid');
        $rel['name'] = $varr[$rid];
        $rel['receive_time'] = time();
        db("prize_pool")->insert($rel);
        exit(json_encode(array('status'=>1,'result'=>$res,'user_id'=>session('user_id'))));       
    }    
       
    /**
     * 算出概率函数
     **/
   public function get_rand($proArr) {   
    $result = '';    
    //概率数组的总概率精度   
    $proSum = array_sum($proArr);    
    
    //概率数组循环   
    foreach ($proArr as $key => $proCur) {   
        $randNum = mt_rand(1, $proSum);   
        if ($randNum <= $proCur) {   
            $result = $key;   
            break;   
        } else {   
            $proSum -= $proCur;   
        }         
    }   
    unset ($proArr);    
    return $result;   
}   
       
       
       /*********************************************************/
       /*****************微信获取关注和不关注的代码*****************/
       /*********************************************************/
       /**
        *
        * 通过跳转获取用户的openid，跳转流程如下：
        * 1、设置自己需要调回的url及其其他参数，跳转到微信服务器https://open.weixin.qq.com/connect/oauth2/authorize
        * 2、微信服务处理完成之后会跳转回用户redirect_uri地址，此时会带上一些参数，如：code
        *
        * @return 用户的openid
        */
       public function index()
       {
             $code = input('param.code');
               //通过code获得openid
               if (empty($code)){
                   //触发微信返回code码
                   $baseUrl = urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING']);
                   $url = $this->__CreateOauthUrlForCode($baseUrl);
                   Header("Location: $url");
                   exit();
               } else {
                   $openid = $this->getOpenidFromMp($code);
                   $access_token = $this->get_access_token();
                   session('openid',$openid);
                   session('token',$access_token);
                   $wx_union_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$access_token}&openid={$openid}&lang=zh_CN";
                   $wx_union = curl_request($wx_union_url);
                   $wx_union_array = json_decode($wx_union,true);
                   $attention = db('user');
                   $attention_info = $attention->where(array("openid"=>$wx_union_array['openid']))->find();
                   if($attention_info==""){
                           $data['openid'] = $wx_union_array['openid'];
                           $data['sm_time'] = time();
                           $attention->insert($data);
                   }
                   if(empty($wx_union_array['subscribe'])||$wx_union_array['subscribe']==0){
                       header("Location:".Url('follow_wx'));
                   }else{   
                       $rew['head_pic'] = $wx_union_array['headimgurl'];
                       $rew['nickname'] = $wx_union_array['nickname'];
                       $attention->where(array("id"=>$attention_info['id']))->update($rew);
                       session('user_id',$attention_info['id']);//给上面 存入记录表用的
                       header('Location:'.Url('redenvelope'));
                   }
               }
       }
       
       /**
        * 获取Access_token
        * @author HZH
        */
       private  function get_access_token(){
           $access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->wx_config['appid']}&secret={$this->wx_config['appsecret']}";
           $access_token_json = curl_request($access_token_url);
           $access_token = json_decode($access_token_json,true)['access_token'];
           return $access_token;
       }
        
       /**
        *
        * 通过code从工作平台获取openid机器access_token
        * @param string $code 微信跳转回来带上的code
        *
        * @return openid
        */
       private function GetOpenidFromMp($code)
       {
           $url = $this->__CreateOauthUrlForOpenid($code);
           //初始化curl
           $ch = curl_init();
           //设置超时
           curl_setopt($ch, CURLOPT_TIMEOUT, 30);
           curl_setopt($ch, CURLOPT_URL, $url);
           curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
           curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
           curl_setopt($ch, CURLOPT_HEADER, FALSE);
           curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
           if($this->wx_config['curl_proxy_host']!= "0.0.0.0"
               && $this->wx_config['curl_proxy_port'] != 0){
                   curl_setopt($ch,CURLOPT_PROXY,$this->wx_config['curl_proxy_host']);
                   curl_setopt($ch,CURLOPT_PROXYPORT, $this->wx_config['curl_proxy_port']);
           }
           //运行curl，结果以jason形式返回
           $res = curl_exec($ch);
           curl_close($ch);
           //取出openid
           $data = json_decode($res,true);
           $this->data = $data;
           $openid = $data['openid'];
           return $openid;
       }
        
        
       /**
        *
        * 构造获取code的url连接
        * @param string $redirectUrl 微信服务器回跳的url，需要url编码
        *
        * @return 返回构造好的url
        */
       private function __CreateOauthUrlForCode($redirectUrl)
       {
           $urlObj["appid"] = $this->wx_config['appid'];
           $urlObj["redirect_uri"] = "$redirectUrl";
           $urlObj["response_type"] = "code";
           $urlObj["scope"] = "snsapi_base";
           $urlObj["state"] = "STATE"."#wechat_redirect";
           $bizString = $this->ToUrlParams($urlObj);
           return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
       }
        
       /**
        *
        * 构造获取open和access_toke的url地址
        * @param string $code，微信跳转带回的code
        *
        * @return 请求的url
        */
       private function __CreateOauthUrlForOpenid($code)
       {
           $urlObj["appid"] = $this->wx_config['appid'];
           $urlObj["secret"] = $this->wx_config['appsecret'];
           $urlObj["code"] = $code;
           $urlObj["grant_type"] = "authorization_code";
           $bizString = $this->ToUrlParams($urlObj);
           return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
       }
        
       /**
        *
        * 拼接签名字符串
        * @param array $urlObj
        *
        * @return 返回已经拼接好的字符串
        */
       private function ToUrlParams($urlObj)
       {
           $buff = "";
           foreach ($urlObj as $k => $v)
           {
               if($k != "sign"){
                   $buff .= $k . "=" . $v . "&";
               }
           }
           $buff = trim($buff, "&");
           return $buff;
       }
        
        
   /*********************************************************/
   /*****************推送图文活动到公众号上*****************/
   /*********************************************************/
        /***
         * 推送模版
         * **/
    public function responseMsg()//执行接收器方法 
    { 
    $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; 
    if (!empty($postStr)){ 
      $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); 
      $RX_TYPE = trim($postObj->MsgType); 
      $RX_EVENT = trim($postObj->Event); 
      $RX_FROMUSERNAME = trim($postObj->FromUserName); 
      if($RX_TYPE=="event" && $RX_EVENT=="subscribe"){
          $attention = db('user')->where(array("openid"=>$RX_FROMUSERNAME))->find();
          if($attention){
              $result = $this->receiveEvent($postObj); 
          }else{
              $content = "欢迎关注“Call管家食品”。五谷为养，喝Call管家。
Call管家， 用心构筑甜美生活";//这里是向关注者发送的提示信息
              $result = $this->textEvent($postObj,$content); 
          }
      }else if($RX_TYPE == 'text'){
          $content = trim($postObj->Content);//消息内容  
             if(!empty( $content )){
                 $reply_data = db('wx_reply')->where(array("key"=>$content))->find();
                 if($reply_data){
                     if($reply_data['dtype']==1){
                         $graphic_data = db('wx_graphic')->where(array('id'=>$reply_data['graphic_id']))->find();
                         $access_token = $this->get_access_token();
                         $url="https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=".$access_token;
                         $filedata = array( 'media_id'=> $graphic_data['media_id']);
                         $filedata = json_encode($filedata,true);
                         $ch1 = curl_init ();
                         curl_setopt ( $ch1, CURLOPT_URL, $url );
                         curl_setopt ( $ch1, CURLOPT_POST, 1 );
                         curl_setopt ( $ch1, CURLOPT_RETURNTRANSFER, 1 );
                         curl_setopt ( $ch1, CURLOPT_CONNECTTIMEOUT, 5 );
                         curl_setopt ( $ch1, CURLOPT_SSL_VERIFYPEER, FALSE );
                         curl_setopt ( $ch1, CURLOPT_SSL_VERIFYHOST, false );
                         curl_setopt ( $curl, CURLOPT_SAFE_UPLOAD, true); //php版本5.6 得加这句
                         curl_setopt ( $ch1, CURLOPT_POSTFIELDS, $filedata );
                         $resu = curl_exec ( $ch1 );
                         curl_close ( $ch1 );
                         $resu = json_decode($resu, true);
                         $material_data = db('wx_material')->where(array('media_id'=>$resu['news_item'][0]['thumb_media_id']))->field('url')->find();
                         $result = $this->transmitText($postObj,$resu['news_item'][0]['title'],$resu['news_item'][0]['digest'],$material_data['url'],$resu['news_item'][0]['url']);
                     }else{
                         $result = $this->textEvent($postObj,$reply_data['content']); 
                     }
                 }else{
                     $content = "查找不到你想要的！";//这里是向关注者发送的提示信息 
                     $result = $this->textEvent($postObj,$content); 
                 }
             }  
      }
      echo $result; 
  }else{ 
   echo ""; 
   exit; 
  } 
 } 
 
 //活动回复  
  private function receiveEvent($object){ 
   $title = "抽奖活动";//这里是向关注者发送的提示信息 
   $description1 = "“红包积分兑，喝出幸福感！”/“赚积分，兑红包！”/“袋袋有惊喜，红包任性兑”";//这里是向关注者发送的提示信息 
   $picurl = "http://huangmai.ozkoalas.cn/Public/images/hb.jpg";//这里是向关注者发送的提示信息 
   $url = "http://huangmai.ozkoalas.cn/index.php/Home/Activity/test";
   $result = $this->transmitText($object,$title,$description1,$picurl,$url); 
   return $result; 
 } 
 public function test(){
        $qrcode = db("prize_qrcode")->where(array("id"=>session('qrcode_id')))->find();
        $url = "http://huangmai.ozkoalas.cn/index.php/Home/Activity/card/?only=".$qrcode['only'];
        header("Location:".$url);
 }
 private function transmitText($object,$title,$description1,$picurl,$url){ 
   $textTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[news]]></MsgType>
    <ArticleCount>1</ArticleCount>
    <Articles>
    <item>
    <Title><![CDATA[%s]]></Title> 
    <Description><![CDATA[%s]]></Description>
    <PicUrl><![CDATA[%s]]></PicUrl>
    <Url><![CDATA[%s]]></Url>
    </item>
    </Articles>
    </xml>";
    $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(),$title,$description1,$picurl,$url); 
    return $result; 
  }
  
 //文字回复   因为开启了url  原公众号回复暂时暂停
 private function textEvent($object,$content){ 
   $result = $this->transmitTexts($object,$content); 
   return $result; 
 } 
 private function transmitTexts($object,$content){ 
   $textTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[%s]]></Content>
    </xml>";
    $result = sprintf($textTpl, $object->FromUserName, $object->ToUserName, time(),$content); 
    return $result; 
  }
  
   /*********************************************************/
   /*****************用户中奖记录*****************/
   /*********************************************************/
  public function record(){
      $user_id = input('user_id');
      $user_info = db("user")->where(array("id"=>$user_id))->find();
      $list = db('prize_pool')->where(array("user_id"=>$user_id))->order("id desc")->select();
      $this->assign("user_info",$user_info);
      $this->assign("list",$list);
      return $this->fetch('record');
  }
  
  /****************************
   * 自定义菜单
   */
  public function menu(){
      $access_token=$this ->get_access_token();
      echo $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$access_token;
      $list = db('wx_menu')->where(array('parent_id'=>0))->select();
      foreach($list as &$vo){
            $vo['cate'] = db('wx_menu')->where(array('parent_id'=>$vo['id']))->select();
      }
      
      $postArr = [
          'button' => []
      ];
      
      foreach ($list as $vo){
          $parent_button = [
              'name'=>urlencode($vo['menu_name']),
              'sub_button'=>[],
          ];
          foreach($vo['cate'] as $v){
              $sub_button = [
                    'name'=>urlencode($v['menu_name']),
                    'type'=>'view',
                    'url'=>$v['menu_url'],
              ];
              $parent_button['sub_button'][] = $sub_button;
          }
          $postArr['button'][]=$parent_button;
      }
   
        $postJson = urldecode(json_encode($postArr));
        $res = $this->http_curl($url,'post','json',$postJson);
        var_dump($res);
  }
  
  public function menudel(){
      $access_token=$this ->get_access_token();
      echo $url = 'https://api.weixin.qq.com/cgi-bin/menu/delete?access_token='.$access_token;
  }
  
   //$url  接口url string
    //$type 请求类型string
    //$res  返回类型string
    //$arr= 请求参数string
    public function http_curl($url,$type='get',$res='json',$arr=''){

        //1.初始化curl
        $ch  =curl_init();
        //2.设置curl的参数
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

        if($type == 'post'){
            curl_setopt($ch,CURLOPT_POST,1);
            curl_setopt($ch,CURLOPT_POSTFIELDS,$arr);
        }
        //3.采集
        $output =curl_exec($ch);

        //4.关闭
        curl_close($ch);
        if($res=='json'){
            if(curl_error($ch)){
                //请求失败，返回错误信息
                return curl_error($ch);
            }else{
                //请求成功，返回错误信息

                return json_decode($output,true);
            }
        }
        echo var_dump( $output );
    }     
}